#include "SnaillTcpClient.h"

SnaillTcpClient* SnaillTcpClient::m_instance = nullptr;
SnaillTcpClient::SnaillTcpClient(QObject *parent) : QObject(parent)
{
    m_socket = new QTcpSocket(this);
    connect(m_socket, &QTcpSocket::readyRead, this, &SnaillTcpClient::onReadyRead);
}
SnaillTcpClient::~SnaillTcpClient()
{
    disconnectFromServer();
}

SnaillTcpClient* SnaillTcpClient::instance()
{
    if (m_instance == nullptr) {
        m_instance = new SnaillTcpClient;
    }
    return m_instance;
}

bool SnaillTcpClient::connectToServer(const QString &host, quint16 port)
{
    m_socket->connectToHost(host, port);
//    if (m_socket->waitForConnected()) {
//           qDebug() << "Connected to server";
//       } else {
//           qDebug() << "Failed to connect to server:" << m_socket->errorString();
//       }
//    return false;
    return m_socket->waitForConnected();
}

bool SnaillTcpClient::sendJsonData(const QJsonObject &jsonData)
{
    if (m_socket->state() == QTcpSocket::ConnectedState) {
        QJsonDocument jsonDoc(jsonData);
        QByteArray jsonDataBytes = jsonDoc.toJson(QJsonDocument::Compact);
        qint64 bytesWritten = m_socket->write(jsonDataBytes);
        m_socket->flush();
        return bytesWritten == jsonDataBytes.size();
    }
    return false;
}

void SnaillTcpClient::disconnectFromServer()
{
    if (m_socket->state() == QTcpSocket::ConnectedState) {
        m_socket->disconnectFromHost();
        m_socket->waitForDisconnected();
    }
}

void SnaillTcpClient::onReadyRead()
{
    QByteArray data = m_socket->readAll();
    emit dataReceived(data);
}
